package pers.cz.business;

import cn.hutool.core.date.DateUtil;
import pers.cz.mapper.*;
import pers.cz.model.*;
import pers.cz.mybatisPlugin.PageRowBounds;
import pers.cz.pub.AbstractBusiness;
import pers.cz.pub.SequenceEnum;
import pers.cz.spring.SpringContextUtil;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

/**
 * @program: PostGirl-panent
 * @description: SystemConfigBusiness
 * @author: Cheng Zhi
 * @create: 2022-01-13 21:39
 **/
public class SystemConfigBusiness extends AbstractBusiness {

    /**
     * 查询所有角色返回树形结构
     * @return
     */
    public List<Role> getAllRole() {

        return this.getMapper(RoleMapper.class).selectRoles();
    }

    public Role getRoleById(Integer roleId) {

        return  this.getMapper(RoleMapper.class).selectRoleById(roleId);
    }

    /**
     * 根据父id获取所有孩子节点
     * @param ParentRoleId
     * @return
     */
    public List<Role> getRolesByParentId(Integer ParentRoleId) {
        return this.getMapper(RoleMapper.class).selectRolesByParentId(ParentRoleId);
    }

    /**
     * 获取所有节点的祖宗节点，这里是admin
     * @return
     */
    public List<Role> getAllParentRole() {

        return this.getMapper(RoleMapper.class).selectAllParentRoles();
    }

    /**
     * 获取该角色下所有的菜单
     * @param roldId
     * @return
     */
    public List<Power> getAllMenuId(Integer roldId) {

        return this.getMapper(PowerMapper.class).getAllMenuId(roldId);
    }

    /**
     * 新增角色，同时新增一个role_power
     * @param role
     * @return
     */
    public Integer addRole(Role role) {

        Long menuId = cPublicFunc.getSoNbr(SequenceEnum.MENU_ID_SEQUENCE);
        // 这里采用多线程，插入到Role表即可，其他的事情通过多线程去处理。异步插入
        FutureTask<String> futureTask = new FutureTask<>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(10000);
                // 先查询role表
                RolePower rolePower = new RolePower();
                rolePower.setPowerId(Integer.valueOf(menuId + ""));
                rolePower.setRoleId(Integer.valueOf(menuId + ""));

                SpringContextUtil.getBean(RolePowerMapper.class).insert(rolePower);
                return null;
            }
        });
        ExecutorService executor = Executors.newFixedThreadPool(1);
        executor.submit(futureTask);
        executor.shutdown();
        role.setRoleId(Integer.valueOf(menuId +""));
        return this.getMapper(RoleMapper.class).insert(role);
    }

    /**
     * 修改角色
     * @param role
     * @return
     */
    public Integer updateRole(Role role) {
        return this.getMapper(RoleMapper.class).updateSelective(role);
    }

    /**
     * 删除一个角色，删除的同时删除角色对应的能力，以及能力菜单
     * @param roleId
     * @return
     */
    public Integer deleteRole(Integer roleId) {

        return this.getMapper(RoleMapper.class).deleteByPrimaryKey(roleId);
    }

    /**
     * 新增角色能力对应的菜单权限
     * @param roleId
     * @param menuId
     * @return
     */
    public Integer addPower(Integer roleId, Integer menuId) {

        Power power = new Power();
        power.setPowerId(roleId);
        power.setMenuId(menuId);
        return this.getMapper(PowerMapper.class).insert(power);
    }

    /**
     * 删除角色对应的菜单权限
     * @param roleId
     * @param menuId
     * @return
     */
    public Integer deletePower(Integer roleId, Integer menuId) {

        return this.getMapper(PowerMapper.class).deleteByMenuId(menuId);
    }

    /**
     * 查询所有用户的信息
     * @return
     */
    public List<PostgirlDtl> queryAllUserDtl() {

        return this.getMapper(PostgirlDtlMapper.class).queryAllUserDtl();
    }

    public List<PostgirlDtl> queryAllUserDtlByPage(Integer limit, Integer state) {

        PageRowBounds pageRowBounds = new PageRowBounds(state, limit);
        return this.getMapper(PostgirlDtlMapper.class).queryAllUserDtlByPage(pageRowBounds);
    }

    /**
     * 添加用户: 插用户表，插用户角色表， 插用户明细信息表
     * @param postgirl
     * @return
     */
    public Integer addUser(Postgirl postgirl) {

        Long userId = cPublicFunc.getSoNbr(SequenceEnum.USER_ID_SEQUENCE);
        postgirl.setUserId(Integer.valueOf(userId + ""));
        postgirl.setCreateDate(DateUtil.date());
        postgirl.setUpdateDate(DateUtil.date());
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        postgirl.setPassWord(bCryptPasswordEncoder.encode(postgirl.getPassWord()));
        postgirl.setAccountExpired("1");
        postgirl.setCredentialsExpired("1");
        this.getMapper(PostgirlMapper.class).insertSelective(postgirl); // 插用户表

        Role role = postgirl.getRoles().get(0);
        UserRole userRole = new UserRole();
        userRole.setRoleId(Long.valueOf(role.getRoleId()));
        userRole.setUserId(Long.valueOf(postgirl.getUserId()));
        this.getMapper(UserRoleMapper.class).insertSelective(userRole); // 插用户角色表

        PostgirlDtl postgirlDtl = new PostgirlDtl();
        postgirlDtl.setUserId(Integer.valueOf(userId + ""));
        postgirlDtl.setPhoneId(Long.valueOf(postgirl.getPhoneId()));
        postgirlDtl.setEmail(postgirl.getEmail());
        postgirlDtl.setRealName(postgirl.getRealName());
        Integer count = this.getMapper(PostgirlDtlMapper.class).insertSelective(postgirlDtl); // 插明细表

        return count;
    }

    public Integer updateUser(Postgirl postgirl) {

        this.getMapper(PostgirlMapper.class).updateByPrimaryKeySelective(postgirl); // 修改用户表

        PostgirlDtl postgirlDtl = new PostgirlDtl();
        postgirlDtl.setUserId(postgirl.getUserId());
        postgirlDtl.setPhoneId(Long.valueOf(postgirl.getPhoneId()));
        postgirlDtl.setEmail(postgirl.getEmail());
        postgirlDtl.setRealName(postgirl.getRealName());
        this.getMapper(PostgirlDtlMapper.class).updateByPrimaryKeySelective(postgirlDtl); // 修改明细表

        Role role = postgirl.getRoles().get(0);
        UserRole userRole = new UserRole();
        userRole.setRoleId(Long.valueOf(role.getRoleId()));
        userRole.setUserId(Long.valueOf(postgirl.getUserId()));
        Integer count = this.getMapper(UserRoleMapper.class).updateByUserId(userRole);

        return count;
    }

    /**
     * 删除用户
     * @param userId
     * @return
     */
    public Integer deleteUser(Integer userId) {

        // 删除用户表
        this.getMapper(PostgirlMapper.class).deleteByPrimaryKey(userId);
        // 删除明细表
        this.getMapper(PostgirlDtlMapper.class).deleteByPrimaryKey(userId);
        // 删除用户角色表
        Integer count = this.getMapper(UserRoleMapper.class).deleteByUserId(userId);
        return count;
    }

    /**
     * 重置密码
     * @param userId
     * @return
     */
    public Integer resetPassword(Integer userId, String password) {

        // 加密处理
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        Integer count = this.getMapper(PostgirlMapper.class).updatePasswordByUserId(userId, bCryptPasswordEncoder.encode(password));

        return count;
    }
    /**
     * 获取用户总数
     * @return
     */
    public Integer getCount() {

        PostgirlDtlExample postgirlExample = new PostgirlDtlExample();
        postgirlExample.setOrderByClause("count");

        int count = this.getMapper(PostgirlDtlMapper.class).countByExample(postgirlExample);

        return count;
    }

    /**
     * 修改用户锁定状态
     * @param userId
     * @param locked
     * @return
     */
    public Integer updateLockedState(Integer userId, Integer locked) {

        Postgirl postgirl = new Postgirl();
        postgirl.setUserId(userId);
        postgirl.setLocked(String.valueOf(locked));
        return this.getMapper(PostgirlMapper.class).updateByPrimaryKeySelective(postgirl);
    }

    /**
     * 修改用户禁用状态
     * @param userId
     * @param enable
     * @return
     */
    public Integer updateEnableState(Integer userId, Integer enable) {
        Postgirl postgirl = new Postgirl();
        postgirl.setUserId(userId);
        postgirl.setEnabled(String.valueOf(enable));
        return this.getMapper(PostgirlMapper.class).updateByPrimaryKeySelective(postgirl);
    }

    /**
     * 根据用户id获取用户角色信息
     * @param userId
     * @return
     */
    public Integer getCurrentRoleByUserId(Integer userId) {

        List<UserRole> userRoleList = this.getMapper(UserRoleMapper.class).selectRoleByUserId(userId);
        return Integer.valueOf(userRoleList.get(0).getRoleId() + "");
    }

    /**
     * 根据用户Id获取用户明细信息
     * @param userId
     * @return
     */
    public PostgirlDtl getCurrentUserDtlByUserId(Integer userId) {

        Postgirl postgirl = this.getMapper(PostgirlMapper.class).selectByPrimaryKey(userId);
        PostgirlDtl postgirlDtl = this.getMapper(PostgirlDtlMapper.class).selectByPrimaryKey(userId);

        postgirlDtl.setAccountExpired(postgirl.getAccountExpired());
        postgirlDtl.setCreateDate(postgirl.getCreateDate());
        if (postgirl.isEnabled()) {
            postgirlDtl.setEnabled("1");
        } else {
            postgirlDtl.setEnabled("2");
        }
        postgirlDtl.setCredentialsExpired(postgirl.getCredentialsExpired());
        postgirlDtl.setLocked(postgirl.getLocked());
        postgirlDtl.setPassWord(postgirl.getPassWord());
        postgirlDtl.setUpdateDate(postgirl.getUpdateDate());
        postgirlDtl.setUserName(postgirl.getUserName());
        return postgirlDtl;
    }

}
